package com.zmyuan.demo.netty.combine.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

import java.net.URI;

/**
 * Created by zdb on 2017/2/14.
 */
public class CombineClientTest {

    public static void main(String[] args) {

        int port = 8999;
        String host = "localhost";
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpRequestEncoder())
                            .addLast(new HttpObjectAggregator(65536))
                            .addLast(new HttpResponseDecoder())
                            .addLast(new CombineClientHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // (5)

            URI uri = new URI("http://localhost:8999");
            ByteBuf content = Unpooled.wrappedBuffer("hello".getBytes("UTF-8"));
            DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.GET,
                    uri.toASCIIString(),
                    content);
            req.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            req.headers().set(HttpHeaderNames.HOST, "127.0.0.1");
            req.headers().set(HttpHeaderNames.CONTENT_TYPE, content.readableBytes());
            req.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);


            f.channel().writeAndFlush(req);

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }


    }
}
